package com.zw.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zw.hrm.feignclients.RedisFeignClient;
import com.zw.hrm.util.AjaxResult;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MyLoginFilter extends ZuulFilter {
    @Autowired
    private RedisFeignClient redisFeignClient;


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //从请求上下文中获取当前请求，找到URI，判断URI资源是否放行
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        if (requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //从请求头中获取token，判断token
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)){
            errorResponse();
            return null;
        }
        //请求中token存在，从redis中查询token，并判断查询结果，1.不存在2.token不匹配
        AjaxResult ajaxResult = redisFeignClient.get(token);
        if (!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
            errorResponse();
            return null;
        }
        return null;
    }

    //错误方法
    private void errorResponse(){
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        //设置相应格式，以及响应状态码
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(Response.SC_UNAUTHORIZED);
        //停止执行，并返回错误信息
        currentContext.setSendZuulResponse(false);
        AjaxResult ajaxResult = AjaxResult.me().setSuccess(false).setMessage("请先登录");
        try {
            PrintWriter writer = response.getWriter();
            writer.print(JSON.toJSONString(ajaxResult));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
